package org.iati.mobile;

import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.iati.mobile.exception.IATIBadFilterException;

public class Filter {
	@IatiEntity(path="sector~@code")
	private List<String> sectorIds;

	@IatiEntity(path="participating-org~@ref")
	private List<String> donorIds;

	@IatiEntity(path="reporting-org~@ref")
	private List<String> reportingOrgIds;

	@IatiEntity(path="recipient-country~@code")
	private List<String> countryIds;


	public Filter() {};

	public Filter(List<String> sectorIds, List<String> donorIds,
			List<String> reportingOrgIds, List<String> countryIds) {
		this.sectorIds = sectorIds;
		this.donorIds = donorIds;
		this.reportingOrgIds = reportingOrgIds;
		this.countryIds = countryIds;
	}

	public List<String> getSectorIds() {
		return sectorIds;
	}
	public void setSectorIds(List<String> sectorIds) {
		this.sectorIds = sectorIds;
	}
	public List<String> getDonorIds() {
		return donorIds;
	}
	public void setDonorIds(List<String> donorIds) {
		this.donorIds = donorIds;
	}
	public List<String> getReportingOrgIds() {
		return reportingOrgIds;
	}
	public void setReportingOrgIds(List<String> reportingOrgIds) {
		this.reportingOrgIds = reportingOrgIds;
	}
	public List<String> getCountryIds() {
		return countryIds;
	}
	public void setCountryIds(List<String> countryIds) {
		this.countryIds = countryIds;
	}


	public void addDonorId( String id) {
		if ( this.donorIds == null )
			this.donorIds	= new ArrayList<String>();
		this.donorIds.add(id);
	}

	public void addSectorId( String id) {
		if ( this.sectorIds == null )
			this.sectorIds	= new ArrayList<String>();
		this.sectorIds.add(id);
	}
	public void addReportingOrgId( String id) {
		if ( this.reportingOrgIds == null )
			this.reportingOrgIds	= new ArrayList<String>();
		this.reportingOrgIds.add(id);
	}
	public void addCountryId( String id) {
		if ( this.countryIds == null )
			this.countryIds	= new ArrayList<String>();
		this.countryIds.add(id);
	}

	public String generate() throws IATIBadFilterException {
		StringBuilder ret	= new StringBuilder(100);
		Field[] fields		= Filter.class.getDeclaredFields();
		if (fields != null) {
			for (Field field : fields) {
				try {
					Object value			= field.get(this);
					if ( value != null && value instanceof List) {
						List<Object> list		= (List<Object>) value;
						IatiEntity iatiEntity	= field.getAnnotation(IatiEntity.class);
						if ( list.size() > 0 && iatiEntity != null && 
								iatiEntity.path() != null && iatiEntity.path().length() > 0 ) {
							ret.append("/" + iatiEntity.path() + "/");
							for (int i=0; i<list.size(); i++) {
								Object o	= list.get(i);
								ret.append( URLEncoder.encode(o.toString(), "UTF-8") );
								if ( i < list.size()-1 )
									ret.append(",");
							}
						}
					}
				} catch (Exception e) {
					throw new IATIBadFilterException(e);
				}
			}
		}
		return ret.toString();
	}
}
